package com.bole.controller;


import com.alibaba.fastjson.JSONObject;
import com.bole.data.Result;
import com.bole.data.ResultEnum;
import com.bole.dto.car.BrowsingHistoryDto;
import com.bole.dto.car.TbCarDto;
import com.bole.dto.user.UserDto;
import com.bole.feign.CarFeign;
import com.bole.feign.reception.BroHistoryFeign;
import com.bole.feign.reception.UserServiceFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@Api(value = "浏览记录管理api")
@Controller
@CrossOrigin
@RequestMapping("broHistory")
public class BrowsingHistoryController {

    @Autowired
    private BroHistoryFeign broHistoryFeign;

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Autowired
    private CarFeign carFeign;

    @RequestMapping("toList")
    @ApiOperation(value = "跳转浏览页面")
    public String toList() {
        return "histroy";

    }
    //查询浏览记录
    @ResponseBody
    @PostMapping("selectByUserId")
    public Result selectByUserId(){
        Subject subject = SecurityUtils.getSubject();
        UserDto userDto = (UserDto) subject.getPrincipal();
        List<BrowsingHistoryDto> browsingHistoryDtos = broHistoryFeign.selectByUserId(userDto.getId());
        TbCarDto carById = new TbCarDto();
        List<TbCarDto> carDtos = new ArrayList<>();
        for (BrowsingHistoryDto browsingHistoryDto : browsingHistoryDtos) {
           // System.out.println(browsingHistoryDto);
            Long carId = browsingHistoryDto.getCarId();
            carById = carFeign.getCarById(carId);
            carDtos.add(carById);
            System.out.println(carById);
        }
       // System.out.println(browsingHistoryDtos);
        return Result.response(ResultEnum.OK).setData(carDtos);
    }


    //添加浏览记录
    @ResponseBody
    @PostMapping("addHistory")
    @ApiOperation(value = "通过fitstChar查询",notes = "通过fitstChaar查询")
    @ApiImplicitParam(name = "carId", value = "关联类型ID", required = true, dataTypeClass = Long.class)
    public Result addCart(@RequestParam("cookie")String cookie,@RequestParam("carId") Long carId) {
            UserDto user = userServiceFeign.getUserByTelePhone(cookie);
            //如果登录了，存到monggodb
            broHistoryFeign.saveHistory(user.getId(),carId);
            return Result.response(ResultEnum.OK);
        }

}
